<script setup lang="ts">
import { useViewportStore } from '@renderer/stores/viewport'
import { ViewHelper } from 'three/examples/jsm/Addons.js'
import { watchEffect } from 'vue'
import { storeToRefs } from 'pinia'
import { Clock } from 'three'

const viewportStore = useViewportStore()
const { camera, renderer, viewHelper } = storeToRefs(viewportStore)

watchEffect(() => {
  const container = document.getElementById('viewport')
  if (camera?.value && renderer.value && container) {
    viewportStore.setViewHelper(new ViewHelper(camera.value, container))
    renderer.value.autoClear = false
  }
})

function handleClick(event: any) {
  event.stopPropagation()
  // 点击后视口转换与预想不一致
  // viewHelper.value.handleClick(event)
}

const clock = new Clock()
function animate() {
  const delta = clock.getDelta()
  if (renderer.value) {
    if (viewHelper.value && camera.value) {
      viewHelper.value.render(renderer.value)
      if (viewHelper.value.animating === true) {
        viewHelper.value.update(delta)
      }
    }
  }
  requestAnimationFrame(animate)
}
setTimeout(() => {
  animate()
})
</script>

<template>
  <div id="viewHelper" @click="handleClick"></div>
</template>

<style lang="scss" scoped>
#viewHelper {
  position: absolute;
  right: 0px;
  bottom: 0px;
  height: 128px;
  width: 128px;
  z-index: 1;
}
</style>
